﻿using InterfaceService;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Model.JWT;
using Model.Response;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using System.IdentityModel.Tokens.Jwt;

namespace Service
{
    public class CustomJWTService : ICustomJWTService
    {
        private readonly JWTTokenOptions _JWTTokenOptions;

        public CustomJWTService(IOptionsMonitor<JWTTokenOptions> jwtTokenOptions)
        {
            _JWTTokenOptions = jwtTokenOptions.CurrentValue;
        }

        public async Task<string> GetToken(UserRes user)
        {
            var result = await Task.Run(() => 
            {
                //身份验证成功 步骤一：生成用户的Claims（无需消息传递也可不写）
                var claims = new List<Claim>
                {
                    new Claim("Id", user.Id),
                    new Claim("NickName", user.NickName),
                    new Claim("Name", user.Name),
                    new Claim("UserType", user.UserType.ToString()),
                    new Claim("Image", user.Image==null?"":user.Image)
                };

                //步骤二：生成加密key:
                //Nuget引入：Microsoft.IdentityModel.Tokens;
                SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_JWTTokenOptions.SecuritKey));

                //步骤三：根据加密key生成一个票据
                SigningCredentials creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //步骤四：生成JWT返回的Token
                //Nuget引入：System.IdentityModel.Tokens.Jwt;
                JwtSecurityToken jwtToken = new JwtSecurityToken(
                    issuer: _JWTTokenOptions.Issuer,
                    audience: _JWTTokenOptions.Audience,
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(10),//10分钟有效
                    notBefore: null,
                    signingCredentials: creds);

                string token = new JwtSecurityTokenHandler().WriteToken(jwtToken);

                return token;
            });

            return result;
        }
    }
}
